package co.chuangdian.oflauncher.widgets.setting;

import co.chuangdian.oflauncher.R;
import uc.SettingListView;
import uc.Setting;
import uc.SettingGroup;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.appwidget.AppWidgetHost;
import android.appwidget.AppWidgetManager;
import android.appwidget.AppWidgetProviderInfo;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.ImageButton;
import cn.onekit.CALLBACK;
import cn.onekit.CONFIG;
import cn.onekit.DIALOG;
import cn.onekit.JSON;
import cn.onekit.MESSAGE;

public class ManageFragment extends Fragment {

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
		return inflater.inflate(R.layout.widgetsetting_manage, container, false);
	}

	SettingGroup[] settingGroups;
	JSONArray systemWidgetsJSON, customWidgetsJSON;
	ImageButton addButton;
	JSONArray allWidgets;
	SettingListView list;
	ImageButton editButton;
	ImageButton hideButton;
	ImageButton deleteButton;
	Map<String, Integer> indexes = new HashMap<String, Integer>();

	public void onActivityCreated(Bundle savedInstanceState) {
		super.onActivityCreated(savedInstanceState);
		mAppWidgetManager = AppWidgetManager.getInstance(getActivity());
		mAppWidgetHost = new AppWidgetHost(getActivity(), APPWIDGET_HOST_ID);
		// 开始监听widget的变化
		mAppWidgetHost.startListening();
		list = (SettingListView) getActivity().findViewById(R.id.settingListView);
		addButton = (ImageButton) getActivity().findViewById(R.id.addButton);
		// editButton=list.ed
		addButton.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				showWidgetChooser();

			}

		});
		//		
		allWidgets = JSON.parses((String) CONFIG.get("widgets"));
		reloadData();
	}

	/*
	 * Drawable gettitleicon(JSONObject widget) { Drawable drawable = null; if
	 * (widget.optBoolean("system")) {
	 * 
	 * switch (widget.optInt("id")) { case -1: drawable =
	 * getActivity().getResources().getDrawable(R.drawable.icon_weather); break;
	 * case -2: drawable =
	 * getActivity().getResources().getDrawable(R.drawable.icon_music); break;
	 * 
	 * case -3: drawable =
	 * getActivity().getResources().getDrawable(R.drawable.icon_quick); break;
	 * 
	 * case -4: drawable =
	 * getActivity().getResources().getDrawable(R.drawable.icon_connect); break;
	 * 
	 * case -5: drawable =
	 * getActivity().getResources().getDrawable(R.drawable.icon_setting); break;
	 * 
	 * default: break; }
	 * 
	 * } else {
	 * 
	 * drawable = ((ACTIVITY)
	 * getActivity()).getResources().getDrawable(R.drawable.icon_camera);
	 * 
	 * } return drawable; }
	 */
	void reloadData() {
		MESSAGE.send("widgets", null, null);

		indexes.clear();
		List<Setting> systemWidgets = new ArrayList<Setting>();
		List<Setting> customWidgets = new ArrayList<Setting>();
		for (int i = 0; i < allWidgets.length(); i++) {
			JSONObject widget = allWidgets.optJSONObject(i);
			@SuppressWarnings("deprecation")

			// Drawable drawable = ((ACTIVITY)
			// getActivity()).getResources().getDrawable(R.drawable.icon_camera);
			boolean isSystem = widget.optBoolean("system");

			Setting setting = new Setting(geticon(widget), widget.optString("name"), !isSystem,
					widget.optBoolean("hidden"));
			if (isSystem) {
				indexes.put(0 + "," + systemWidgets.size(), i);
				systemWidgets.add(setting);
			} else {
				indexes.put(1 + "," + customWidgets.size(), i);
				customWidgets.add(setting);
			}
		}
		settingGroups = new SettingGroup[] { new SettingGroup(1, "OF Launcher插件", systemWidgets), new SettingGroup(2, "自定义", customWidgets) };
		list.setData(settingGroups, new CALLBACK<int[]>() {

			@Override
			public void run(boolean isError, int[] result) {
				if (isError) {
					return;
				}
				final JSONObject widget = allWidgets.optJSONObject(getIndex(result));
				// final JSONObject widget = getWidget(result);
				DIALOG.input("请输入新名称?", new CALLBACK<String>() {

					@Override
					public void run(boolean isError, String result) {
						if (isError) {
							return;
						}
						try {
							widget.put("name", result);
							CONFIG.set("widgets", allWidgets);
							reloadData();
						} catch (Exception e) {
							e.printStackTrace();
						}
					}

				});

			}
		}, new CALLBACK<int[]>() {

			@Override
			public void run(boolean isError, int[] result) {
				if (isError) {
					return;
				}
				final JSONObject widget = allWidgets.optJSONObject(getIndex(result));

				final boolean hidden = widget.optBoolean("hidden");
				String msg;
				if (hidden) {

					msg = "已经隐藏，是否设置显示？";
				} else {
					msg = "已经显示，是否设置隐藏？";
				}
				try {
					DIALOG.confirm(msg, new CALLBACK<Object>() {

						@Override
						public void run(boolean isError, Object result) {
							if (isError) {
								return;
							}
							try {

								widget.put("hidden", !hidden);
								CONFIG.set("widgets", allWidgets);
								reloadData();

								DIALOG.toast("设置成功");
							} catch (Exception e) {
								e.printStackTrace();
							}
						}

					}, new CALLBACK<Object>() {
						public void run(boolean isError, Object result) {
						};
					});
					/*
					 * ImageButton viewbutton = (ImageButton) view; if (hidden)
					 * {
					 * 
					 * viewbutton.setImageResource(R.drawable.btn_hide_off); }
					 * else {
					 * viewbutton.setImageResource(R.drawable.btn_hide_on); }
					 */
				} catch (Exception e) {
					e.printStackTrace();
				}

			}
		}, new CALLBACK<int[]>() {

			@Override
			public void run(boolean isError, int[] result) {
				if (isError) {
					return;
				}
				final JSONObject widget = allWidgets.optJSONObject(getIndex(result));
				try {
					DIALOG.confirm("是否删除?", new CALLBACK<Object>() {

						@Override
						public void run(boolean isError, Object result) {
							if (isError) {
								return;
							}
							try {
								List<Object> list = new ArrayList<Object>();
								for (int i = 0; i < allWidgets.length(); i++) {
									list.add(allWidgets.get(i));
									JSONObject gardenJson = (JSONObject) allWidgets.get(i);
									if (widget.equals(gardenJson)) {
										list.remove(i);
									}
								}
								allWidgets = new JSONArray(list);
								CONFIG.set("widgets", allWidgets);
								reloadData();
							} catch (JSONException e) {
								e.printStackTrace();
							}
						}

					}, new CALLBACK<Object>() {
						public void run(boolean isError, Object result) {
						};
					});

				} catch (Exception e) {
					e.printStackTrace();
				}

			}
		});
	}

	private Drawable geticon(JSONObject widget) {
		Drawable drawable = null;
		if (widget.optBoolean("system")) {

			switch (widget.optInt("id")) {
			case -1:
				drawable = getActivity().getResources().getDrawable(R.drawable.icon_weather_grey);
				break;
			case -2:
				drawable = getActivity().getResources().getDrawable(R.drawable.icon_music_grey);
				break;

			case -3:
				drawable = getActivity().getResources().getDrawable(R.drawable.icon_quick_grey);
				break;

			case -4:
				drawable = getActivity().getResources().getDrawable(R.drawable.icon_connect_grey);
				break;

			case -5:
				drawable = getActivity().getResources().getDrawable(R.drawable.icon_setting_grey);
				break;

			default:
				break;
			}

		} else {
			int appWidgetId = widget.optInt("id");
			AppWidgetProviderInfo widgetInfo = mAppWidgetManager.getAppWidgetInfo(appWidgetId);
			drawable = getActivity().getPackageManager().getDrawable(widgetInfo.provider.getPackageName(),
					widgetInfo.icon, null);

		}
		return drawable;
	}

	int getIndex(int[] result) {
		return indexes.get(result[0] + "," + result[1]);
	}
	/*
	 * JSONObject getWidget(int[] result) { return null; }
	 */

	private AppWidgetHost mAppWidgetHost;
	private AppWidgetManager mAppWidgetManager;
	private static final int REQUEST_PICK_APPWIDGET = 1;
	private static final int REQUEST_CREATE_APPWIDGET = 2;
	private static final int APPWIDGET_HOST_ID = 0x100; // 用于标识
	private static final String EXTRA_CUSTOM_WIDGET = "custom_widget";
	private int icon;

	@Override
	public void onActivityResult(int requestCode, int resultCode, Intent data) {
		if (resultCode == Activity.RESULT_OK) {
			switch (requestCode) {
			case REQUEST_PICK_APPWIDGET:
				addAppWidget(data);
				break;
			case REQUEST_CREATE_APPWIDGET:
				completeAddAppWidget(data);
				break;
			}
		} else if (requestCode == REQUEST_PICK_APPWIDGET && resultCode == Activity.RESULT_CANCELED && data != null) {
			// Clean up the appWidgetId if we canceled
			int appWidgetId = data.getIntExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, -1);
			if (appWidgetId != -1) {
				mAppWidgetHost.deleteAppWidgetId(appWidgetId);
			}
		}
	}

	/**
	 * 选中了某个widget之后，根据是否有配置来决定直接添加还是弹出配置activity
	 * 
	 * @param data
	 */
	private void addAppWidget(Intent data) {
		int appWidgetId = data.getIntExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, -1);

		String customWidget = data.getStringExtra(EXTRA_CUSTOM_WIDGET);
		Log.d("addAppWidget", "data:" + customWidget);
		if ("search_widget".equals(customWidget)) {
			// 这里直接将search_widget删掉了
			mAppWidgetHost.deleteAppWidgetId(appWidgetId);
		} else {
			AppWidgetProviderInfo appWidget = mAppWidgetManager.getAppWidgetInfo(appWidgetId);

			Log.d("addAppWidget", "configure:" + appWidget.configure);
			if (appWidget.configure != null) {
				// 有配置，弹出配置
				Intent intent = new Intent(AppWidgetManager.ACTION_APPWIDGET_CONFIGURE);
				intent.setComponent(appWidget.configure);
				intent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, appWidgetId);
				startActivityForResult(intent, REQUEST_CREATE_APPWIDGET);
			} else {
				// 没有配置，直接添加
				completeAddAppWidget(data);
			}
		}
	}

	/**
	 * 请求添加一个新的widget:用于选取系统中的widget
	 */
	private void showWidgetChooser() {
		int appWidgetId = mAppWidgetHost.allocateAppWidgetId();
		Intent pickIntent = new Intent(AppWidgetManager.ACTION_APPWIDGET_PICK);
		pickIntent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, appWidgetId);
		startActivityForResult(pickIntent, REQUEST_PICK_APPWIDGET);
	}

	String currwidget = "";

	/**
	 * 添加widget
	 * 
	 * @param data
	 */
	@SuppressWarnings("deprecation")
	private void completeAddAppWidget(Intent data) {
		Bundle extras = data.getExtras();

		int appWidgetId = extras.getInt(AppWidgetManager.EXTRA_APPWIDGET_ID, -1);
		AppWidgetProviderInfo appWidgetInfo = mAppWidgetManager.getAppWidgetInfo(appWidgetId);
		JSONObject widget = new JSONObject();
		try {
			widget.put("id", appWidgetId);
			widget.put("system", false);
			widget.put("name", appWidgetInfo.label);
			widget.put("size", "8x8");
			widget.put("hidden", false);
			allWidgets.put(widget);
			CONFIG.set("widgets", allWidgets);
			reloadData();

		} catch (JSONException e) {
			e.printStackTrace();
		}
	}

}
